package wxapp

import (
	"context"
	"errors"
	"hotgo/internal/service"
	"time"

	"github.com/golang-jwt/jwt/v5"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"

	v1 "hotgo/api/api/wxapp/v1"
)

func (c *ControllerV1) Login(ctx context.Context, req *v1.LoginReq) (res *v1.LoginRes, err error) {
	res = &v1.LoginRes{}
	loginRes, errs := c.wxappHandler.Auth.Session(ctx, req.Code)
	if nil != errs {
		return nil, errs
	}
	if 0 != loginRes.ErrCode {
		return nil, errors.New(loginRes.ErrMsg)
	}
	theUser, errs := service.Wxapp().InsertWxappUser(ctx, loginRes.OpenID, loginRes.SessionKey)
	if nil != errs {
		return nil, errs
	}

	// Create claims with user information
	claims := &JWTClaims{
		Openid: loginRes.OpenID,
		Phone:  theUser.Phone,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * 24 * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}

	// Generate token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signedToken, err := token.SignedString(c.jwtKey)
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeInternalError, "Failed to generate token")
	}
	res.Token = signedToken
	res.HasPhone = theUser.Phone != ""
	return res, nil
}
